package com.healthcarex.hip.saas.common.util.tree;


import com.healthcarex.hip.saas.common.model.Tree;

import java.util.ArrayList;
import java.util.List;

/**
 * @author chenpan
 * @ClassName: TreeUtils
 * description:
 * @date 2018-05-15 10:20
 */

public class TreeUtils {

    public static <T extends Tree> List<T> buildTree(List<T> treeDatas) {
        List<T> trees = null;
        if (treeDatas != null && !treeDatas.isEmpty()) {
            trees = new ArrayList<>();
            for (T tree : treeDatas) {
                //根
                if (tree.getParentId() == null || tree.getParentId() == 0) {
                    tree.setChildren(buildChildren(tree, treeDatas));
                    trees.add(tree);
                }
            }
        }
        return trees;
    }

    private static <T extends Tree> List<T> buildChildren(T tree, List<T> trees) {
        List<T> children = getChilds(tree, trees);
        if (children != null && !children.isEmpty()) {
            for (T sub : children) {
                sub.setChildren(buildChildren(sub, trees));
            }
        }
        return children;
    }

    private static <T extends Tree> List<T> getChilds(T tree, List<T> trees) {
        List<T> childs = new ArrayList<>();
        for (T it : trees) {
            if (tree.getId().equals(it.getParentId())) {
                childs.add(it);
            }
        }
        return childs;
    }
}